package com.sdx.console.customer.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.saas.entity.SaasTenant;
import com.sdx.console.utils.BigDecimalUntil;
import com.sdx.console.utils.EDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName CustomerRegisterCountController
 * @Description 注册会员统计
 * @Author kangbin
 * @Date 2019/12/3 11:20
 */
@RequestMapping("/customer/register")
@Controller
public class CustomerRegisterCountController extends AuthorizedBaesController {
    private static final Logger log = LoggerFactory.getLogger(CustomerRegisterCountController.class);
    private static final String MODEL = "/customer/register";

    private static final String SQL = "customer.register";

    @Resource
    private SQLManager sqlManager;

    @Resource
    private BaseDataService baseDataService;

    @Autowired
    private CorePlatformService platformService;

    /**
     * 初始化页面需要的列表数据，
     * @param view 业务模块，来源渠道
     */
    private void setPageParam(ModelAndView view,HttpServletRequest request) {

        view.addObject("provinceList",baseDataService.getAllProvince());
        Integer accessType = platformService.getAccessType(request);
        view.addObject("accessType",accessType);
        if (accessType==6) {
            SaasTenant param = new SaasTenant();
            param.setTenantStatus(1);
            List<SaasTenant> tenantList = sqlManager.template(param);
            view.addObject("tenantList", tenantList);
        }
    }

    @GetMapping("/index.do")
    @Function("customer.register.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }

    @PostMapping("/list.json")
    @Function("customer.register.query")
    @ResponseBody
    public JsonResult<List<BaseEntity>> list(String date, Integer type, Integer provinceId, HttpServletRequest request,Integer tenantId) {
        Date parse =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
           if(StringUtils.isNotBlank(date)){
               parse = sdf.parse(date);
           }
        }catch (Exception e){
            e.printStackTrace();
        }
        CoreUser user = getLoginUser(request);
        Integer accessType = platformService.getAccessType(request);
        String year = EDateUtil.getYear(parse);
        String month = EDateUtil.getMonth(parse);
        Map<String,Object> param = new HashMap<>();
        param.put("year",year);
        param.put("month",month);
        if(provinceId!=null&&provinceId==0){
            provinceId=null;
        }
        param.put("provinceId",provinceId);
        param.put("tenantId",user.getTenantId());
        if(accessType==6&&tenantId!=null){
            param.put("tenantId",tenantId);
        }
        List<BaseEntity> list = new ArrayList<>();
        List<BaseEntity> lists = new ArrayList<>();
        int count = 0;
        int length = 12;
        if(type!=null&&type==2){
            lists = sqlManager.select(SQL+".selectRegisterByMonth", BaseEntity.class,param);
            count = sqlManager.intValue(SQL+".selectRegisterByMonthCount",param);
            //获取月份的最后一天
            Calendar calendar =Calendar.getInstance();
            calendar.setTime(parse);
            Date monthEnd = EDateUtil.getMonthEnd(calendar);
            length =  Integer.parseInt(EDateUtil.getDay(monthEnd));
        }else{
            //年报表
            lists = sqlManager.select(SQL+".selectRegisterByYear", BaseEntity.class,param);
            count = sqlManager.intValue(SQL+".selectRegisterByYearCount",param);
        }
        for (int i = 1; i <= length; i++) {
            BaseEntity entity = new BaseEntity();
            entity.set("date",i);
            int total = 0;
            for (BaseEntity baseEntity : lists) {
                if(i ==Integer.parseInt(baseEntity.get("date").toString())){
                    total = Integer.parseInt(baseEntity.get("total").toString());
                    break;
                }
            }
            double rate = 0;
            if(count>0){
              rate = BigDecimalUntil.rate(total,count,2);
            }
            entity.set("total",total);
            entity.set("rate",rate);
            list.add(entity);
        }
        return JsonResult.success(list);
    }

}
